var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.STOCK20;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'stock/check/batch_page';

var Utils = {
	doQueryDepot : function(){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'stock'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#ba_dp_code").val(selected.dp_code);
					$("#depot_name").val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#ac_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"stock/check/to_batch_add";
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'view'){
			url = config.BASEPATH+"stock/check/to_batch_view?ba_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'approve'){
			url = config.BASEPATH+"stock/check/to_batch_view?ba_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'check_add'){
			url = config.BASEPATH+"stock/check/to_check_add?ba_id="+id;
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'check_view'){
			var rowData =$("#grid").jqGrid("getRowData", id);
			url = config.BASEPATH+"stock/check/to_check_view?ba_id="+id+"&ck_number="+rowData.ck_number;
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'check_view_all'){
			url = config.BASEPATH+"stock/check/to_check_view_all?ba_id="+id;
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'check_exec'){
			url = config.BASEPATH+"stock/check/to_check_exec?ba_id="+id;
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'check_diff'){
			var rowData =$("#grid").jqGrid("getRowData", id);
			url = config.BASEPATH+"stock/check/to_check_diff?fromJsp=check_batch&ba_number="+rowData.ba_number;
			data = {oper: oper, callback:this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false
		}).max();
	},
	del: function(rowId){//删除
		var rowData = $("#grid").jqGrid("getRowData", rowId);
	 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'stock/check/batch_delete',
				data:{"number":rowData.ba_number},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$('#grid').jqGrid('delRowData', rowId);
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});	
    },
    callback: function(data, oper, dialogWin){
		if(oper == "approve") {
			THISPAGE.reloadData();
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "add"){
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == 'view'){
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == "check_add"){
			Public.tips({type: 3, content : '盘点成功'});
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == "check_exec"){
			THISPAGE.reloadData();
			if(data.state == 'exec_succ'){
				Public.tips({type: 3, content : '处理成功!'});
				dialogWin && dialogWin.api.close();
			}
		}
	},
	formatScope:function(val, opt, row){
		if(val == 0){
			return '全场盘点';
		}else if(val == 1){
			return '类别盘点';
		}else if(val == 2){
			return '品牌盘点';
		}else if(val == 3){
			return '单品盘点';
		}else if(val == 4){
			return '年份盘点';
		}else if(val == 5){
			return '季节盘点';
		}
		return val;
	},
	formatArState:function(val, opt, row){//0：未审核；1：已审核2：已退回
		if(val == 0){
			return '未审核';
		}else if(val == 2){
			return '已退回';
		}else if(val == 1){
			if(row.ba_isexec == 0){
				return '盘点中';
			}else if(row.ba_isexec == 1){
				return '全部处理';
			}else if(row.ba_isexec == 2){
				return '部分处理';
			}
		}
		return val;
	},
	formatExec : function(val, opt, row){
		if (row.ba_ar_state != '1') {
			return '';
		}
		if(row.ba_isexec != 0){
    		return '完成';
    	}
		var btnHtml = '';
		btnHtml += '<input type="button" value="处理" class="btn_ck" onclick="javascript:handle.operate(\'check_exec\',' + opt.rowId + ');" />';
		return btnHtml;
	},
	formatNumberLink : function(val, opt, row){
		var btnHtml = '';
		if (row.ba_ar_state != '1') {
			btnHtml += '<a href="javascript:void(0);" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');">'+row.ba_number+'</a>';
		}else{
			btnHtml += '<a href="javascript:void(0);" onclick="javascript:handle.operate(\'check_view_all\',' + opt.rowId + ');">'+row.ba_number+'</a>';
		}
		return btnHtml;
	},
	formatGapAmount:function(val, opt, row){
		if($.trim(row.ba_amount) == '' || $.trim(row.ba_stockamount) == ''){
			return '';
		}
		return row.ba_amount-row.ba_stockamount;
	},
	operFmatter : function(val, opt, row){
		var btnHtml = '';
		if (row.ba_ar_state == '0') {
            btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
        }else if (row.ba_ar_state == '2') {
            btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        }else if (row.ba_ar_state == '1') {//审核通过
        	if(row.ba_isexec == 0){
        		if($.trim(row.ck_number) == ""){
        			btnHtml += '<input type="button" value="录入" class="btn_xg" onclick="javascript:handle.operate(\'check_add\',' + opt.rowId + ');" />';
        		}else{
        			btnHtml += '<input type="button" value="已盘" class="btn_ck" onclick="javascript:handle.operate(\'check_view\',' + opt.rowId + ');" />';
        		}
        	}else{
        		if($.trim(row.ck_number) == ""){
        			btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        		}else{
        			btnHtml += '<input type="button" value="已盘" class="btn_ck" onclick="javascript:handle.operate(\'check_view\',' + opt.rowId + ');" />';
        		}
        	}
        }
		btnHtml += '<input type="button" value="流程" class="btn_qh" onclick="javascript:listBillProcess(\''+row.ba_number+'\',\'t_stock_batch\');" />';
		
		if(row.ba_isexec != 0){
			btnHtml += '<input type="button" value="盘点差异明细" style="width:80px;" class="btn_ck" onclick="javascript:handle.operate(\'check_diff\',' + opt.rowId + ');" />';
    	}
		
		return btnHtml;
	}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.$_ar_state = $("#ar_state").cssRadio({ callback: function($_obj){
			$("#ba_ar_state").val($_obj.find("input").val());
		}});
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 180, formatter: handle.operFmatter,align:'left', sortable:false},
	    	{name: 'exec',label:'处理',width: 60, formatter: handle.formatExec,align:'center', sortable:false},
	    	{name: 'ba_isexec',label:'',index: 'ba_isexec',width:100,hidden:true},
	    	{name: 'ck_number',label:'',index: 'ck_number',width:100,hidden:true},
	    	{name: 'ba_number',label:'',index: 'ba_number',width:100,hidden:true},
	    	{name: 'numberlink',label:'单据编号',index: 'ba_number',width:150,formatter: handle.formatNumberLink},
	    	{name: 'depot_name',label:'盘点仓库',index: 'ba_dp_code',width:120},
	    	{name: 'ba_scope',label:'盘点范围',index: 'ba_scope',width:80,formatter: handle.formatScope},
	    	{name: 'ba_amount',label:'盘点数量',index: 'ba_amount',width:80,align:'right'},
	    	{name: 'ba_stockamount',label:'库存数量',index: 'ba_stockamount',width:80,align:'right'},
	    	{name: 'gap_amount',label:'差异数量',index: '',width:80,align:'right',formatter: handle.formatGapAmount},
	    	{name: 'ba_manager',label:'经办人',index: 'ba_manager',width:100},
	    	{name: 'ba_date',label:'制单日期',index: 'ba_date',width:80},
	    	{name: 'ba_ar_state',label:'状态',index: 'ba_ar_state',width:80,formatter: handle.formatArState}
	    	
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'ba_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'ba_ar_state='+$("#ba_ar_state").val();
		params += '&begindate='+$("#begindate").val();
		var enddate = $("#enddate").val();
		if(enddate != ""){
			params += '&enddate='+enddate+' 23:59:59';
		}else{
			params += '&enddate='+$("#enddate").val();
		}
		params += '&ba_dp_code='+$("#ba_dp_code").val();
		params += '&ba_manager='+Public.encodeURI($("#ba_manager").val());
		params += '&ba_number='+Public.encodeURI($("#ba_number").val());
		return params;
	},
	reset:function(){
		$("#depot_name").val("");
		$("#ba_dp_code").val("");
		$("#ba_number").val("");
		$("#ba_manager").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_ar_state.setValue(0);
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var rowId = $('#grid').jqGrid('getGridParam','selrow');
			if(rowId == null || rowId == ''){
				Public.tips({type: 1, content : "您未选择任何数据"});
				return;
			}
			var rowData =$("#grid").jqGrid("getRowData", rowId);
			if(rowData.ba_ar_state != "未审核" && rowData.ba_ar_state != "已退回"){
				Public.tips({type: 1, content : "单据已审核，不能删除"});
				return;
			}
			handle.del(rowId)
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
	}
}
THISPAGE.init();